package table_user

import (
	"gitee.com/klein-x/biz/model/mysql/table"
	"gitee.com/klein-x/biz/module/db/mysql"
	"gitee.com/klein-x/biz/xutils"
	"gorm.io/gorm"
)

type UserInfoWithAnswer struct {
	ID           string         `gorm:"primaryKey;type:char(36);unique;not null;comment:'交互记录ID'"`
	UserUUID     string         `gorm:"type:char(36);not null;comment:'用户UUID'"`
	PaperID      string         `gorm:"type:char(36);not null;comment:'试卷ID'"`
	QuestionID   string         `gorm:"type:char(36);not null;comment:'题目ID'"`
	AnswerCardID string         `gorm:"type:char(36);not null;comment:'答题卡ID'"`
	IsWrong      string         `gorm:"type:char(1);not null;default:'0';comment:'是否错题, 否 0, 是 1'"`
	DeletedAt    gorm.DeletedAt `gorm:"comment:'软删除时间'"`
}

func (uia *UserInfoWithAnswer) TableName() string {
	return "user_info_with_answer"
}
func WrongQuestionGetByUsers(userUUID string) (*[]UserInfoWithAnswer, error) {
	db := mysql.GetGlobalDB()

	var usersInfo []UserInfoWithAnswer
	return table.SelectCheck(&usersInfo, db.Where("user_uuid = ? AND is_wrong = 1", userUUID).Find(&usersInfo))
}

func WrongQuestionSet(userUUID string, paperID string, questionID string, AnswerCardID string, IsWrong bool) error {
	db := mysql.GetGlobalDB() // 获取全局数据库连接实例

	var isW string
	if IsWrong {
		isW = "1"
	} else {
		isW = "0"
	}

	var userInfo UserInfoWithAnswer
	// 全局查询, 然后判断delete字段可以知道是插入还是更新
	userInfoPtr, err := table.SelectCheck(&userInfo, db.Unscoped().Where(
		"user_uuid = ? AND paper_id = ? AND question_id = ? AND answer_card_id = ?",
		userUUID, paperID, questionID, AnswerCardID).
		First(&userInfo))
	if err != nil {
		return err
	}

	if userInfoPtr == nil { // 如果指针等于空,说明没查到 那就启用插入逻辑
		var info UserInfoWithAnswer
		uuid, err := xutils.RandomUUID()
		if err != nil {
			return err
		}
		info.ID = uuid
		info.UserUUID = userUUID
		info.PaperID = paperID
		info.QuestionID = questionID
		info.AnswerCardID = AnswerCardID
		info.IsWrong = isW
		return table.InsertCheck(db.Create(&info))
	} else {
		return table.UpdateCheck(
			db.Model(&UserInfoWithAnswer{}).
				Where("user_uuid = ? AND paper_id = ? AND question_id = ? AND answer_card_id = ?",
					userUUID, paperID, questionID, AnswerCardID).
				Updates(map[string]interface{}{
					"is_wrong":   isW,
					"deleted_at": gorm.Expr("NULL"),
				}))
	}
}

// 重置错题
func WrongQuestionResetByAnswerCardID(answerCardId string) error {
	db := mysql.GetGlobalDB()
	return table.UpdateCheck(
		db.Model(&UserInfoWithAnswer{}).
			Where("answer_card_id = ?", answerCardId).
			Updates(map[string]interface{}{
				"is_wrong":   "0",
				"deleted_at": gorm.Expr("NULL"),
			}))
}
func WrongQuestionResetByUserAndPaper(userUUID string, paperID string) error {
	db := mysql.GetGlobalDB()

	var answer UserInfoWithAnswer
	return db.Where("user_uuid = ? AND paper_id =", userUUID, paperID).Delete(&answer).Error
}
